import React, { useEffect, useState } from 'react';
import { Button, Drawer, Form, Select, Input, message, Tooltip } from 'antd';
import { CopyOutlined } from '@ant-design/icons';
import wrapper from '@utils/wrapper';
import Copy from 'copy-to-clipboard';
import appApi from '@request/app_manage';
import serverApi from '@request/server_manage';
import { AppRecord, serverInfo } from '..';
import {ServerRecord} from '../../server_manage';
import {apiTypes} from '../../mock';
import './index.less';


interface CreateAppModalProps {
  type: 'add' | 'edit' | 'view',
  record: AppRecord,
  visible: boolean,
  closeDialog: () => void,
  getList: () => void,
}
const actionType = {
  add: '新建',
  edit: '编辑',
  view: '查看'
}
const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
}
const Option = Select.Option;
interface FormFieldsValue {

}
interface AddAppParams {
  name: string,
  server_infos: serverInfo[],
  type: string, 
  desc: string
  id?: number
}
const CreateAppModal = ({
  type,
  record,
  visible,
  getList,
  closeDialog
}: CreateAppModalProps) => {
  const [form] = Form.useForm();
  const [serverList, setServerList] = useState<ServerRecord[]>([]);
  const [serverType, setServerType] = useState<string | undefined>();
  const { getFieldValue, validateFields, setFieldsValue } = form;
  const disabled = type === 'view' ? true : false;
  useEffect(() => {
    if (['view', 'edit'].includes(type)) {
      setFieldsValue({
        name: record.name,
        desc: record.desc,
        type: record.type,
        server_name: record.server_infos.map(item => item.id)
      })
      setServerType(record.type);
    }
  }, []);
  useEffect(() => {
    // 请求服务列表
    serverApi.getServerList()
      .then(res => {
        setServerList(res.data);
      })
  }, []);
  const onOk = () => {
    if (type === 'view') return closeDialog && closeDialog();
    validateFields()
      .then(async (info) => {
        let params: AddAppParams = {
          name: info.name,
          desc: info.desc,
          type: info.type,
          server_infos: []
        }
        info.server_name.forEach((id: number) => {
          let serverInfo: ServerRecord = serverList.find((item: ServerRecord) => item.id === id)!;
          params.server_infos.push({
            id: serverInfo.id,
            name: serverInfo.name
          })
        })
        serverList.find((item: ServerRecord) => item.id)
        if (type === 'add') {
          await appApi.createApp({
            body: params
          })
        } else {
          await appApi.updateApp({
            body: {
              ...params,
              id: record.id
            }
          })
        }
        closeDialog && closeDialog();
        getList && getList();
      })
  }
  const copy = (type: 'private_key' | 'public_key') => {
    let res = Copy(record[type]);
    if (res) {
      message.success('复制成功')
    } else {
      message.error('复制错误')
    }
  }
  const title = actionType[type] + '应用';
  return <Drawer
    visible={visible}
    title={title}
    closable={false}
    width={"40%"}
    className='add-app-modal'
    footer={
      <>
        <Button style={{ float: 'right', marginLeft: '12px' }} type='primary' onClick={onOk}>确定</Button>
        <Button style={{ float: 'right' }} onClick={closeDialog}>取消</Button>
      </>
    }
    onClose={closeDialog}
  >
    <Form form={form} {...layout}>
      <Form.Item
        name='name'
        label='应用名称'
        rules={[
          { pattern: /^[a-z][a-zA-Z_0-9]{0,31}$/g, message: '请输入以小写字母开头，支持_、数字、大小，最大不超过32位的名称' },
          { required: true, message: '请输入应用名称' },
        ]}
      >
        <Input disabled={disabled} placeholder='请输入应用名称' />
      </Form.Item>
      <Form.Item name='type' label='服务类型'>
        <Select disabled={disabled} onChange={(value: string) => setServerType(value)}>
          {
            apiTypes.map(item => {
              return <Option key={item.key} value={item.key}>{item.name}</Option>
            })
          }
        </Select>
      </Form.Item>
      <Form.Item name='server_name' label='服务名称'>
        <Select disabled={disabled} mode="multiple">
          {
            serverList.filter((server: ServerRecord) => server.type === serverType)
              .map((_server: ServerRecord) =>
                <Option key={_server.id} value={_server.id}>{_server.name}</Option>
              )
          }
        </Select>
      </Form.Item>
      <Form.Item name='desc' label='应用描述'>
        <Input.TextArea disabled={disabled} rows={4} />
      </Form.Item>
      {
        ['view'].includes(type) && <>
          <Form.Item name='public_key' label='公钥' className='app-copy-item'>
            <Input.TextArea value={record.public_key} disabled={true} rows={4} />
            <Tooltip title='复制'>
              <CopyOutlined className='icon-copy' onClick={() => copy('private_key')} />
            </Tooltip>
          </Form.Item>
          <Form.Item name='private_key' label='私钥' className='app-copy-item'>
            <Input.TextArea value={record.private_key} disabled={true} rows={4} />
            <Tooltip title='复制'>
              <CopyOutlined className='icon-copy' onClick={() => copy('private_key')} />
            </Tooltip>
          </Form.Item>
        </>
      }
    </Form>
  </Drawer>
}

export default wrapper(CreateAppModal);